from django import forms
from django.contrib import admin
from .models import *

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['id', 'display_name', 'parent', 'is_root', 'sort_order']
    
    def display_name(self, obj):
        return obj.display_name
    display_name.short_description = '分类名称'
    
    list_editable = ['sort_order']  # 允许直接编辑排序
    search_fields = ['name']
    list_filter = ['parent', 'is_root']  # 添加is_root过滤
    
    # 新增：优化表单展示
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'is_root')
        }),
        ('层级关系', {
            'fields': ('parent',),
            'classes': ('collapse',)
        }),
        ('展示设置', {
            'fields': ('sort_order',)
        })
    )
    
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        if db_field.name == 'name' and request.GET.get('is_root') == '1':
            kwargs['widget'] = forms.Select(choices=Category.ROOT_CATEGORIES)
        return super().formfield_for_dbfield(db_field, request, **kwargs)
    
    def get_readonly_fields(self, request, obj=None):
        if obj and obj.is_root:
            return ['parent']
        return []

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['id', 'product_code', 'name', 'price','seller', 'status']
    readonly_fields = ['product_code']  # 设为只读
    list_filter = ['status', 'delivery_method', 'category']
    search_fields = ['name', 'product_code']
# 达梦优化：显式指定索引表空间（需确保SECONDTRADE存在）
    list_select_related = ['category', 'seller']  # 减少查询次数
    # 达梦优化：显式指定索引表空间（需确保SECONDTRADE存在）
    list_select_related = ['category', 'seller']  # 减少查询次数

@admin.register(Favorite)
class FavoriteAdmin(admin.ModelAdmin):
    list_display = ['user', 'product', 'favorited_time']
    raw_id_fields = ['user', 'product']  # 避免加载全部用户/商品

@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
    list_display = ['id', 'product', 'image_url', 'display_order','size']
    list_filter = ['product']
    search_fields = ['product__name']